<?php

use app\App;

function dd($vars)
{
    while (ob_get_level())
    {
        ob_end_clean();
    }
    array_map(function($var) {
        ob_start();
        var_dump($var);
        $out = ob_get_clean();
        echo "<pre><code>$out</code></pre>";
    }, func_get_args());
    die;
}

function config($key, $default = null)
{
    return App::getInstance()->config($key, $default);
}

function url($url)
{
    return App::getInstance()->url($url);
}

function view($view, $data = [])
{
    ob_start();
    extract($data);
    $file = sprintf("%s/%s", VIEW_PATH, trim($view, '/'));
    require $file;
    return ob_get_clean();
}

function session($name, $value = null)
{
    $id = session_id();
    if ($id === '')
    {
        session_start();
    }
    if (is_null($value))
    {
        if (isset($_SESSION[$name]))
        {
            return $_SESSION[$name];
        }
        else 
        {
            return null;
        }
    }
    else 
    {
        return $_SESSION[$name] = $value;
    }
}

function ip_info($ip)
{
    $start = microtime(true);
//    $url = "http://ip.taobao.com/service/getIpInfo.php?ip=$ip";
    $url = "http://freeapi.ipip.net/$ip";
    $result = file_get_contents($url);
    writelog(sprintf('%s cost time: %s s', __FUNCTION__, sprintf('%.4f', microtime(true) - $start)));
    if ($result === false)
    {
        writelog(sprintf('%s failed, url: %s, result: %s', __METHOD__, $url, $result));
        return [];
    }
    
    $infoArr = json_decode($result, true);
    return $infoArr;
    if (isset($infoArr['code']) && $infoArr['code'] == 0 && !empty($infoArr['data']))
    {
        return $infoArr['data'];
    }
    else 
    {
        writelog(sprintf('%s response error, url: %s, result: %s', __METHOD__, $url, $result));
        return [];
    }
}

function writelog($msg, $facility = LOG_INFO)
{
    $filename = date('Ymd');
    file_put_contents(
        RUNTIME_PATH . "/$filename.log", 
        sprintf("%s||%s||%s%s", date('H:i:s'), $facility, $msg, PHP_EOL),
        FILE_APPEND
    );
}

function merge_args(array $defaults, array $args)
{
    foreach ($defaults as $key => &$value)
    {
        if (isset($args[$key]))
        {
            $value = $args[$key];
        }
    }
    return $defaults;
}

function env($name, $default = '')
{
    $value = getenv($name);
    if ($value === false)
    {
        return $default;
    }
    switch (strtolower($value))
    {
        case 'false':
            return false;
            break;
        case 'true':
            return true;
            break;
        case 'null':
            return null;
            break;
    }
    return $value;
}
